package com.pet_service.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pet_service.entity.User;
import com.pet_service.entity.UserAddress;
import com.pet_service.entity.UserRole;
import com.pet_service.enums.TUserRegisterTypeStatus;
import com.pet_service.result.Result;
import com.pet_service.service.LoginService;
import com.pet_service.service.UserAddressService;
import com.pet_service.service.UserRoleService;
import com.pet_service.service.UserService;
import com.pet_service.upload.ImageUploadUtil;
import com.pet_service.vo.LoginVo;
import com.pet_service.vo.RegisterVo;
import com.pet_service.enums.TUserAddressStatus;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * @author 邹全伸
 * @version 1.0
 * @date 2025-10-05 14:18
 */
@Slf4j
@RestController
@RequestMapping("/app/login")
@Tag(name = "登录接口")
public class LoginController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserAddressService userAddressService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/getCode/{phone}")
    @Operation(summary = "获取短信验证码")
    public Result getCode(@PathVariable("phone") String phone) {
        loginService.getSMSCode(phone);
        return Result.ok();
    }

    @PostMapping("/check")
    @Operation(summary = "登录")
    public Result<String> login(@RequestBody LoginVo loginVo) {
        log.info("登录参数：{}", loginVo);
        String token = loginService.login(loginVo);
        log.info("token={}", token);
        return Result.ok(token);
    }

    @PostMapping("/register")
    @Operation(summary = "注册")
    public Result register(@RequestBody RegisterVo registerVo) {
        // 1. 生成 username
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.likeRight("username", "user");
        wrapper.orderByDesc("id");
        wrapper.likeRight("username", "user");
        wrapper.orderByDesc("id");
        List<User> userList = userService.list(wrapper);

        User lastUser = userList.isEmpty() ? null : userList.get(0);

        String nextUsername = "user01";
        if (lastUser != null) {
            int num = Integer.parseInt(lastUser.getUsername().substring(4));
            nextUsername = "user" + String.format("%02d", num + 1);
        }

        // 2. 创建 User 对象
        User user = new User();
        user.setUsername(nextUsername);
        String encodedPassword = passwordEncoder.encode(registerVo.getPassword());
        user.setPassword(encodedPassword);
        user.setPhone(registerVo.getPhone());
        user.setNickname(registerVo.getNickname());
        user.setReal_name(registerVo.getRealName());
        user.setGender(registerVo.getGender());
        user.setRegister_type(TUserRegisterTypeStatus.ACCOUNT_PASSWORD);

        // 3. 保存用户
        boolean userSaved = userService.save(user);
        if (!userSaved) {
            return Result.fail("用户保存失败！");
        }

        // 4. 分配角色：普通用户默认为 CUSTOMER (role_id=3)
        UserRole userRole = new UserRole();
        userRole.setUser_id(user.getId());
        userRole.setRole_id(3); // 普通用户
        userRole.setCreated_at(new Date());
        userRole.setUpdated_at(new Date());

        boolean roleSaved = userRoleService.save(userRole);
        if (!roleSaved) {
            log.error("角色分配失败，用户ID: {}", user.getId());
        }

        // 5. 保存地址（如果提供了）
        if (registerVo.getAddress() != null && !registerVo.getAddress().trim().isEmpty()) {
            UserAddress userAddress = new UserAddress();
            userAddress.setUser_id(user.getId());
            userAddress.setProvince("湖北省");
            userAddress.setCity("武汉市");
            userAddress.setDistrict("江夏区");
            userAddress.setDetail(registerVo.getAddress());
            userAddress.setIs_default(TUserAddressStatus.DEFAULT);
            user.setAvatar_url(registerVo.getAvatarUrl());
            userAddressService.save(userAddress);
        }

        return Result.ok("注册成功！");
    }


    //上传头像
    @PostMapping("/uploadAvatar")
    @Operation(summary = "上传头像")
    public Result uploadAvatar(@RequestParam("avatar") MultipartFile avatar) {
        String url = ImageUploadUtil.upload("user_avatar", avatar);
        return url == null ? Result.fail(500, "上传失败!") : Result.ok(url);
    }

    //删除头像
    @GetMapping("/removeAvatar/{fileName}")
    @Operation(summary = "删除头像")
    public Result removeAvatar(@PathVariable("fileName") String fileName) {
        if (fileName != null) {
            ImageUploadUtil.delete("user_avatar", fileName);
            return Result.ok("删除成功");
        }
        return Result.fail("删除失败");
    }

    //验证手机号
    @GetMapping("/checkPhone/{phone}")
    @Operation(summary = "验证手机号")
    public Result checkPhone(@PathVariable("phone") String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        long count = userService.count(queryWrapper);
        return count > 0 ? Result.fail("手机号已注册!") : Result.ok("手机号可用!");
    }

    //验证用户名
    @GetMapping("/checkUsername/{username}")
    @Operation(summary = "验证用户名")
    public Result checkUsername(@PathVariable("username") String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        long count = userService.count(queryWrapper);
        return count > 0 ? Result.fail("用户名已存在!") : Result.ok("用户名可用!");
    }
}
